package com.jacklin.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Slf4j
@ServerEndpoint("/webSocket")
@Component  //@Component泛指组件，当组件不好归类的时候，我们可以使用这个注解进行标注,意思是把普通pojo实例化到spring容器中，相当于配置文件中的<bean id="" class=""/>
public class WebSocket {

    private Session session;

    //复制写入数组集-用来存储session
    private static CopyOnWriteArraySet<WebSocket> webSocketset = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSocketset.add(this);
        log.info("【webSocket消息】有新的链接，总数：{}",webSocketset.size());
    }

    @OnClose
    public  void onClose(Session session){
        webSocketset.remove(this);
        log.info("【webSocket消息】连接关闭，总数:{}",webSocketset.size());
    }

    @OnMessage
    public void onMessage(String message){
        log.info("【websocket消息】收到客户端发送过来的消息：{}",message);
    }

    public void sendMessage(String message){
        for (WebSocket webSocket:webSocketset){
            log.info("【websocket消息】广播消息，mesagge={}",message);
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
